#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
using namespace std;

const int num = 5;

pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* active(void* args)
{
    string name = static_cast<char*>(args);
    while (true)
    {
        pthread_mutex_lock(&mtx);
        pthread_cond_wait(&cond, &mtx);
        cout << name << " is running..." << endl;
        pthread_mutex_unlock(&mtx);
    }
}

int main()
{
    pthread_t tids[num];

    for (int i = 0; i < num; i++)
    {
        char* name = new char[16];
        snprintf(name, 64, "thread-%d", i+1);

        pthread_create(tids+i, nullptr, active, name);
    }

    sleep(2);

    while (true)
    {
        cout << "main thread signal a cond" << endl;
        // pthread_cond_signal(&cond);
        pthread_cond_broadcast(&cond);
        sleep(1);
    }

    for (int i = 0; i < num; i++)
    {
        pthread_join(tids[i], nullptr);
    }

    return 0;
}
